package com.clotingshoppos.common.base.BaseService;

import com.clotingshoppos.common.base.BaseEntity.BaseEntity;
import com.clotingshoppos.common.base.BaseRepository.BaseRepository;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Optional;

/**
 * @ClassName: BaseServiceImpl
 * @Description:
 * @Author: Izzat
 * @Date: 2019-05-09 13:00
 * @Version: v1.0
 */
public class BaseServiceImpl<T extends BaseEntity, R extends BaseRepository<T>> implements BaseService<T>{
    @Autowired
    private R r;

    @Override
    public T add(T t) {
        return r.save(t);
    }

    @Override
    public T findById(String id) {
        Optional<T> optional = r.findById(id);
        //如果optional为空，须返回null，否则会报错
        return optional.orElse(null);
    }

    @Override
    public T update(T t) {
        if(findById(t.getId()) != null){
            return r.save(t);
        }else
            return null;
    }

    @Override
    public T delete(T t) {
        if(findById(t.getId()) != null){
            r.delete(t);
            return t;
        }else
            return null;
    }
}
